import json
import logging
import http.client

from urllib.error import URLError
from urllib.parse import urlencode

from . import app


SMS_SERVER = '106.ihuyi.com'
SMS_URL = '/webservice/sms.php?method=Submit'
MSG_TEMPLATE = '您的验证码是：%s。请不要把验证码泄露给其他人。'


@app.task
def send_short_message(mobile, code):
    params = urlencode({
        'account': 'C11691813',
        'password': '74968e3779b79784dfe63417e93b4d9b',
        'content': MSG_TEMPLATE % code,
        'mobile': mobile,
        'format': 'json'
    })
    headers = {
        'Content-Type': 'application/x-www-form-urlencoded',
        'Accept': 'text/plain'
    }
    conn = http.client.HTTPConnection(SMS_SERVER, port=80, timeout=10)
    try:
        conn.request('POST', SMS_URL, params, headers)
        json_str = conn.getresponse().read().decode('utf-8')
        return json.loads(json_str)
    except URLError or KeyError as e:
        logging.error(e)
        return json.dumps({
            'code': 500,
            'msg': '短信服务暂时无法使用'
        })
    finally:
        conn.close()
